const ROUTER_VERIFY = {}

const PROTECT_CONFIG = [
  {
    path: '/index2/info2',
    protect: () => {
      return new Promise((resolve, reject) => {
        resolve({flag: false, message: '无权访问'})
      })
    }
  }
]

const addRouterVerify = ({fullPath, id, fun, param}) => {
  if (!ROUTER_VERIFY[fullPath]) {
    ROUTER_VERIFY[fullPath] = []
  }
  ROUTER_VERIFY[fullPath].push({id, fun, param})
}

const removeRouterVerify = (fullPath, id) => {
  if (!ROUTER_VERIFY[fullPath]) {
    return
  }
  ROUTER_VERIFY[fullPath] = ROUTER_VERIFY[fullPath].filter(item => item.id !== id)
}

const getRouterProtectInfo = fullPath => {
  return new Promise(async (resolve, reject) => {
    let currentItem = PROTECT_CONFIG.find(item => item.path == fullPath);
    if (!currentItem && !ROUTER_VERIFY[fullPath]) {
      resolve({flag:true,messageList:[]});
      return
    }
    let protectInfo = true
    let verifyInfo = true
    let messageList = []
    if (currentItem) {
      let {flag, message} = await currentItem.protect();
      messageList.push(message)
      protectInfo = flag
    }
    if (ROUTER_VERIFY[fullPath]) {
      for (let i = 0; i < ROUTER_VERIFY[fullPath]; i++) {
        let {fun, param} = ROUTER_VERIFY[fullPath][i]
        let {flag, message} = await fun(param) && verifyInfo
        if (message && message != '') {
          messageList.push(message)
        }
        verifyInfo = flag && verifyInfo
      }
    }
    resolve({flag: protectInfo && verifyInfo, messageList})
  });
}

export {addRouterVerify, removeRouterVerify, getRouterProtectInfo}
